package git.soulbgm.common;

import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * @author 贺瑞杰
 * @version V1.0
 * @date 2018-06-04 19:35
 * @description 维护TCP连接的Map
 */
public class TcpConnectMap {

    private final static ConcurrentHashMap<Long, NioSocketChannel> connectMap = new ConcurrentHashMap<>();

    public static ConcurrentHashMap<Long, NioSocketChannel> getMap() {
        return connectMap;
    }

    public static void put(Long id, NioSocketChannel channel) {
        connectMap.put(id, channel);
    }

    public static NioSocketChannel get(String id) {
        return connectMap.get(id);
    }

    public static void remove(NioSocketChannel channel) {
        connectMap.entrySet().stream().filter(new Predicate<Map.Entry<Long, NioSocketChannel>>() {
            @Override
            public boolean test(Map.Entry<Long, NioSocketChannel> longChannelEntry) {
                return longChannelEntry.getValue() == channel;
            }
        }).forEach(new Consumer<Map.Entry<Long, NioSocketChannel>>() {
            @Override
            public void accept(Map.Entry<Long, NioSocketChannel> longChannelEntry) {
                connectMap.remove(longChannelEntry.getKey());
            }
        });
    }
}

